package com.yh.csx.crm.service.logic;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yh.b2b.common.response.CommonPageResponse;
import com.yh.b2b.common.response.CommonResultResponse;
import com.yh.b2b.usercenter.facade.stub.UserInfoFacade;
import com.yh.b2b.usercenter.facade.stub.UserSapCusFacade;
import com.yh.b2b.usercenter.facade.stub.vo.SapUserVO;
import com.yh.b2b.usercenter.facade.stub.vo.UserVO;
import com.yh.csx.crm.core.enums.BizError;
import com.yh.csx.crm.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Huang Zhaoping
 * @date 2019/4/11
 */
@Slf4j
@Component
public class UserLogic {

    @Reference
    private UserSapCusFacade userSapCusFacade;

    @Reference
    private UserInfoFacade userInfoFacade;

    @Value("${user.role.id}")
    private Long userRoleId;

    public Long findUserId(String mobile) {
        CommonPageResponse<SapUserVO> rpc = userSapCusFacade.getUserList(mobile, null, null, null, 0, 1);
        if (BizError.SUCCESS.getCode() != rpc.getCode()) {
            throw new BusinessException(rpc.getCode(), rpc.getMessage());
        }
        if (CollectionUtils.isNotEmpty(rpc.getPage().getResult())) {
            return rpc.getPage().getResult().get(0).getId();
        } else {
            return null;
        }
    }

    public Long registerUser(String mobile, String name) {
        CommonResultResponse rpc = userInfoFacade.addQygUser(mobile, name, userRoleId);
        if (BizError.SUCCESS.getCode() != rpc.getCode()) {
            throw new BusinessException(rpc.getCode(), rpc.getMessage());
        }
        if (rpc.getResult() == null) {
            throw new BusinessException("注册用户失败");
        }
        return (Long) rpc.getResult();
    }

    public UserVO getUserById(Long userId) {
        if (Objects.isNull(userId)) {
            return null;
        }
        CommonResultResponse<UserVO> response = userInfoFacade.findUserById(userId);
        if (BizError.SUCCESS.getCode() != response.getCode()) {
            throw new BusinessException(response.getCode(), response.getMessage());
        }
        UserVO userVO = response.getResult();
        if (Objects.isNull(userVO)) {
            throw new BusinessException("注册用户失败");
        }
        return userVO;
    }
}
